import axios from 'axios'
import { getToken } from '../utils/auth'
import Config from '../settings'

// 创建axios实例
const service = axios.create({
  // api 的 base_url
  baseURL: process.env.NODE_ENV === 'production' ? process.env.VUE_APP_BASE_API : '/',
  timeout: Config.timeout // 请求超时时间
})

service.interceptors.request.use(config => {
  console.log('请求发送前拦截')
  this.$loading.service({ fullscreen: true })
  if (getToken()) {
    // 让每个请求携带自定义token 请根据实际情况自行修改
    config.headers['Authorization'] = getToken()
  }
  config.headers['Content-Type'] = 'application/json'
  return config
}, error => {
  this.$loading.close()
  this.$message.error({
    message: '加载超时'
  })
  return Promise.reject(error)
})

// 响应拦截器：在请求响应之后拦截
service.interceptors.response.use(response => {
  console.log('请求响应后处理')
  this.$loading.close()
  return response
}, error => {
  this.$loading.close()
  this.$message.error({
    message: error
  })
  return Promise.reject(error)
})

export default service
